<template>
  <div class="out-container">
    <!-- 操作栏 -->
    <div class="action-bar">
      <el-input
          v-model="searchKeyword"
          placeholder="搜索商品/订单ID/操作人"
          clearable
          style="width: 320px"
          @clear="handleSearch"
      >
        <template #prefix>
          <el-icon>
            <Search/>
          </el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="openDialog('create')">
        <el-icon>
          <Plus/>
        </el-icon>
        新建出库
      </el-button>
    </div>

    <!-- 数据表格 -->
    <el-table
        :data="paginatedData"
        border
        stripe
        style="width: 100%"
    >
      <el-table-column prop="orderId" label="订单ID" width="180" align="center"/>
      <el-table-column prop="productName" label="商品" width="150" align="center"/>
      <el-table-column prop="quantity" label="数量" width="100" align="center"/>
      <el-table-column prop="operator" label="操作人" width="120" align="center"/>
      <el-table-column prop="createTime" label="创建时间" width="180" align="center"/>

      <el-table-column label="出库形式" width="130" align="center">
        <template #default="{ row }">
          <el-tag :type="row.type === '正常出库' ? 'primary' : 'warning'">
            {{ row.type }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="状态" width="100" align="center">
        <template #default="{ row }">
          <el-tag
              v-if="row.type === '借用出库'"
              :type="row.status === '已还' ? 'success' : 'danger'"
          >
            {{ row.status }}
          </el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="180" fixed="right" align="center">
        <template #default="{ row }">
          <el-button link type="primary" @click="openDialog('edit', row)">编辑</el-button>
          <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="filteredData.length"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          background
      />
    </div>

    <!-- 出库弹窗 -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogType === 'create' ? '新建出库' : '编辑出库'"
        width="600px"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="选择商品" prop="productId">
          <el-select
              v-model="form.productId"
              placeholder="请选择商品"
              filterable
              style="width: 100%"
          >
            <el-option
                v-for="product in products"
                :key="product.id"
                :label="product.name"
                :value="product.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="出库形式" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio label="正常出库" @click="changeStatus()" />
            <el-radio label="借用出库"/>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="数量" prop="quantity">
          <el-input-number
              v-model="form.quantity"
              :min="1"
              controls-position="right"
              style="width: 100%"
          />
        </el-form-item>


        <el-form-item
            label="归还状态"
            prop="status"
            v-if="form.type === '借用出库'"
        >
          <el-radio-group v-model="form.status">
            <el-radio label="已还"/>
            <el-radio label="未还"/>
          </el-radio-group>
        </el-form-item>


      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, reactive, computed, onMounted} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {Search, Plus} from '@element-plus/icons-vue'
import {addOutbound, getAllOutBoundInfo, getAllProducts, updateOutbound} from "@/api/auth.js";

// 模拟商品数据
const products = ref([
  {id: 1, name: '笔记本电脑'},
  {id: 2, name: '手机'},
  {id: 3, name: '显示器'}
])
const changeStatus=()=>{
  form.status='无需还'
}
// 模拟出库数据
const rawData = ref([
  {
    id: 1,
    orderId: 'OUT2024001',
    productId: 1,
    productName: '笔记本电脑',
    quantity: 5,
    operator: '张三',
    createTime: '2024-03-01 14:30:00',
    type: '正常出库',
    status: ''
  },
  {
    id: 2,
    orderId: 'OUT2024002',
    productId: 2,
    productName: '手机',
    quantity: 3,
    operator: '李四',
    createTime: '2024-03-02 09:15:00',
    type: '借用出库',
    status: '未还'
  }
])
const initData = async () => {
  try {
    const res = await getAllOutBoundInfo()
    if (res.code === 200) {
      rawData.value = res.data
    } else {
      ElMessage.error(res.message)
    }
  } catch (e) {
    ElMessage.error(e)
  }
  try {
    const res = await getAllProducts()
    if (res.code === 200) {
      products.value = res.data
    } else {
      ElMessage.error(res.message)
    }
  } catch (e) {
    ElMessage.error(e)
  }

}
onMounted(() => {
  initData()
})
// 搜索分页逻辑
const searchKeyword = ref('')
const pagination = reactive({current: 1, size: 10})

const filteredData = computed(() => {
  return rawData.value.filter(item =>
      item.orderId.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
      item.productName.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
      item.operator.toLowerCase().includes(searchKeyword.value.toLowerCase())
  )
})

const paginatedData = computed(() => {
  const start = (pagination.current - 1) * pagination.size
  return filteredData.value.slice(start, start + pagination.size)
})

// 弹窗控制
const dialogVisible = ref(false)
const dialogType = ref('create')
const formRef = ref()
const form = reactive({
  orderId: '',
  productId: null,
  type: '正常出库',
  quantity: 1,
  status: '未还'
})

// 表单验证规则
const rules = {
  productId: [{required: true, message: '请选择商品', trigger: 'change'}],
  type: [{required: true}],
  quantity: [
    {required: true, message: '请输入数量', trigger: 'blur'},
    {type: 'number', min: 1, message: '数量不能小于1'}
  ],
  operator: [{required: true, message: '请选择操作人', trigger: 'change'}]
}

// 生成订单ID
const generateOrderId = () => {
  const datePart = new Date().toISOString().slice(2, 10).replace(/-/g, '')
  return `OUT${datePart}${String(rawData.value.length + 1).padStart(3, '0')}`
}

// 打开弹窗
const openDialog = (type, row) => {
  dialogType.value = type
  if (type === 'edit' && row) {
    Object.assign(form, row)
  } else {
    form.orderId = generateOrderId()
    form.productId = null
    form.type = '正常出库'
    form.quantity = 1
    form.operator = ''
    form.status = '无需还'
  }
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  try {


    if (dialogType.value === 'create') {

      try {
        const res = await addOutbound(form)
        if (res.code === 200) {

          ElMessage.success('添加成功!')
        }else {
          ElMessage.error(res.message)
        }
      } catch (e) {
        ElMessage.error(e)
      }
      await initData()
    } else {
      console.log(form)
  try {
    const res=await updateOutbound(form)
    if (res.code === 200) {
      ElMessage.success('修改成功')
    }else {
      ElMessage.error(res.message)
    }
  }catch (e){
    ElMessage.error(e)
  }

    }


    dialogVisible.value = false
  } catch (error) {
    ElMessage.warning('请完善表单信息')
  }
  await initData()
}

// 删除操作
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定删除订单 ${row.orderId} 吗？`, '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const index = rawData.value.findIndex(item => item.orderId === row.orderId)
    rawData.value.splice(index, 1)
    ElMessage.success('删除成功')
  })
}

// 搜索处理
const handleSearch = () => {
  pagination.current = 1
}
</script>

<style scoped>
.out-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
}

.action-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-table {
  margin-top: 10px;
}

:deep(.el-dialog) .el-form-item__label {
  font-weight: 500;
}
</style>